﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace desktop.db
{
    class MySql : Database
    {
        // MySQL database configuration

        private const string Server   = "localhost";
        private const string Database = "db";
        private const string Username = "root";
        private const string Password = "123456";


        private static object _sync = new object();
        private static MySql _instance;


        private MySqlConnection _conn;
        private MySqlDataReader _rdr;


        private MySql()
        {
            Success = true;
            LastError = string.Empty;

            String connectionStr;
            connectionStr = string.Format("Server={0};Database={1};Uid={2};Pwd={3};", Server, Database, Username, Password);

            try
            {
                _conn = new MySqlConnection(connectionStr);
                _conn.Open();
            }
            catch (MySqlException ex)
            {
                LastError = "MySQL database error: " + ex.Message;
                Success = false;
            }
        }

        public static MySql getInstance()
        {
            if (_instance == null)
            {
                lock (_sync)
                {
                    if (_instance == null)
                    {
                        _instance = new MySql();
                    }
                }
            }

            return _instance;
        }

        #region Properties

        public bool Success
        {
            get;
            private set;
        }

        public string LastError
        {
            get;
            private set;
        }

        #endregion


        public bool ExecuteQuery(string query)
        {
            MySqlCommand cmd = new MySqlCommand(query, _conn);

            if (_rdr != null)
            {
                _rdr.Close();
            }

            _rdr = cmd.ExecuteReader();

            Success = _rdr.HasRows;
            return Success;
        }

        public int getInt(string col)
        {
            _rdr.Read();
            return _rdr.GetInt32(col);
        }

        public decimal getDecimal(string col)
        {
            _rdr.Read();
            return _rdr.GetDecimal(col);
        }
        public string getString(string col)
        {
            _rdr.Read();
            return _rdr.GetString(col);
        }

        public DateTime getDate(string col)
        {
            _rdr.Read();
            return _rdr.GetDateTime(col);
        }

    }
}
